package pingpongdojo.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class UserManager {
	public static interface UserListener {
		public void onSetCurrentUser(User user);
	}

	private User currentUser;
	private Map<String, User> users = new HashMap<String, User>();

	private List<UserListener> listeners = new ArrayList<UserListener>();

	public void addUser(User user) {
		users.put(user.getUserName(), user);
	}

	public User getUser(String username) {
		return users.get(username);
	}

	public void removeUser(User user) {
		users.remove(user.getUserName());
	}

	public User getCurrentUser() {
		return currentUser;
	}

	public void setCurrentUser(User user) {
		this.currentUser = user;

		for (UserListener listener : getListeners()) {
			if (user != null) {
				listener.onSetCurrentUser(user);
			}
		}
	}

	public Set<String> getUserNames() {
		return new TreeSet<String>(users.keySet());
	}

	public void addUserListener(UserListener listener) {
		listeners.add(listener);
	}

	public void removeUserListener(UserListener listener) {
		listeners.remove(listener);
	}

	protected List<UserListener> getListeners() {
		return new ArrayList<UserListener>(listeners);
	}
}
